package com.mxx.pmxt.controller;

import com.alibaba.fastjson.JSONObject;
import com.mxx.pmxt.service.GoodsService;
import com.mxx.pmxt.service.PUserService;
import com.mxx.pmxt.util.FileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;

/**
 * Created by 马潇霄 on 2017/3/23.
 */
@Controller
public class PUserCoutroller
{
    @Resource
    PUserService pUserService;

    @Resource
    GoodsService goodsService;

    @RequestMapping("/login")
    @ResponseBody
    public JSONObject getAllUser()
    {
        return pUserService.getAllUser();
    }

    @RequestMapping("modifyUser")
    public String modifyUser(HttpSession session, String afteruname, String uname, String upassword, String urealname, Integer usex, String utel, String uarea, String uaddress)
    {

        int flag = pUserService.modifyUser(afteruname, uname, upassword, urealname, usex, utel, uarea + " " + uaddress);
        if (flag == 1)
        {
            session.setAttribute("uname", afteruname);
        }
        return "redirect:/showModifyuserinfo";
    }

    @RequestMapping("saveMoney")
    public String saveMoney(HttpSession session, BigDecimal money)
    {

        String name = (String) session.getAttribute("uname");
        String account = pUserService.saveMoney(money, name).toString();
        session.setAttribute("account", account);
        return "redirect:/showIndex";
    }

    @RequestMapping("uploadGoods")
    public String uploadGoods(HttpServletRequest request, HttpSession session, String gname, BigDecimal price, int gkind, String gdetial, @RequestParam("picture") MultipartFile file) throws IOException
    {
        String filename = FileUpload.uploadFile(file, request);
        goodsService.createGoods((String) session.getAttribute("uname"), gname, price, gdetial, filename, gkind);
        return "redirect:/showIndex";
    }


}
